import {initVmSync} from "./utils.js";
import fs from "fs";
import express from "express";
import {ProxyAgent, setGlobalDispatcher} from 'undici'
import bodyParser from "body-parser";
import {metaRouter} from "../metaRouter.js";
import v8 from "v8";
// 设置 HTTP 代理
// const httpDispatcher = new ProxyAgent({uri: "http://127.0.0.1:7890"});
//
// setGlobalDispatcher(httpDispatcher);

let print = console.log
let config = {
    domUrl: 'https://www.google.com/travel/flights/booking?tfs=CBwQAhpJEgoyMDI0LTExLTA2Ih8KA0hLRxIKMjAyNC0xMS0wNhoDTlJUKgJIQjIDMzIwagwIAhIIL20vMDNoNjRyDAgCEggvbS8wN2RmaxpJEgoyMDI0LTExLTIwIh8KA05SVBIKMjAyNC0xMS0yMBoDSEtHKgJIQjIDMzIzagwIAhIIL20vMDdkZmtyDAgCEggvbS8wM2g2NEABSAFwAYIBCwj___________8BmAEB&tfu=CmxDalJJZDFWaVpURnpjbFZxUkc5QlRteFpNMmRDUnkwdExTMHRMUzB0TFhSaVluZHdORUZCUVVGQlIyTlhUMDF6UVdGMk5tZEJFZ1ZJUWpNeU14b0tDSUlQRUFBYUEwaExSRGdjY0piQkFRPT0SBggAIAEoCCIA&hl=en&gl=HK',
    script_name: 'https://www.gstatic.com/',
    debug: false,
    prox: false,
    keepRandom: false,
    body: '',
    cookie: undefined,
    cookie2: undefined,

    type: 'ksada'


}

let t1 = Date.now()

// fetch("http://43.135.155.176:8081/src", {
fetch("http://localhost:8081/src", {
    "headers": {
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "accept-language": "en,en-US;q=0.9,zh-CN;q=0.8,zh;q=0.7,ru;q=0.6",
        "cache-control": "no-cache",
        "pragma": "no-cache",
        "priority": "u=0, i",
        "sec-ch-ua": "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"",
        "sec-ch-ua-arch": "\"x86\"",
        "sec-ch-ua-bitness": "\"64\"",
        "sec-ch-ua-form-factors": "\"Desktop\"",
        "sec-ch-ua-full-version": "\"131.0.6778.86\"",
        "sec-ch-ua-full-version-list": "\"Google Chrome\";v=\"131.0.6778.86\", \"Chromium\";v=\"131.0.6778.86\", \"Not_A Brand\";v=\"24.0.0.0\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-model": "\"\"",
        "sec-ch-ua-platform": "\"macOS\"",
        "sec-ch-ua-platform-version": "\"13.6.9\"",
        "sec-ch-ua-wow64": "?0",
        "sec-fetch-dest": "document",
        "sec-fetch-mode": "navigate",
        "sec-fetch-site": "same-origin",
        "sec-fetch-user": "?1",
        "upgrade-insecure-requests": "1",
        "x-browser-channel": "stable",
        "x-browser-copyright": "Copyright 2024 Google LLC. All rights reserved.",
        "x-browser-validation": "f17l9rSuHmrgo31qEeG2bl8fxeI=",
        "x-browser-year": "2024",
        "x-client-data": "CIS2yQEIpbbJAQipncoBCO30ygEIlKHLAQic/swBCOyYzQEIhqDNAQiyns4BCP6lzgEI0MfOAQj6yc4BCIzKzgEIw8zOAQjGzM4BCKrNzgEI9c/OAQiu0M4BGJuxzgEYgMrOARiT0M4BGOrQzgE="
    },
    "referrerPolicy": "strict-origin-when-cross-origin",
    "body": null,
    "method": "GET",
    "mode": "cors",
    "credentials": "include"
})
// new Promise((resolve) =>{
//     let u = fs.readFileSync("/Users/wang/Documents/meta-search-api/vm/glf1.js").toString()
//     resolve(u)
// })
.then(e => {
        return e.json()
    })
.then(e => {
    e = e;
    e.func = e.func.replace('D4=function(c,k,G,n,S,y,T,t,m,u){for(0;c.H==c;![]!=0){{T=H(c,k)', 'D4=function(c,k,G,n,S,y,T,t,m,u){for(0;c.H==c;![]!=0){{T=H(c,k),pppp(14,k,T.length,T+"","ext",n+"")')
    e.func  = e.func .replace('Sa=function(I,n,r,N,E,x,L,U,Q,T){while(N.O==N){for(x=f(I,N),', 'Sa=function(I,n,r,N,E,x,L,U,Q,T){while(N.O==N){for(x=f(I,N),pppp("Sa", I, x.length, x+"", "ext", r+""),')
    e.func = e.func.replace('B=function(c,k,G,n,S,y,T,t,m){if(k.H==k){{T=p(k,G)', 'B=function(c,k,G,n,S,y,T,t,m){if(k.H==k){{T=p(k,G),pppp(1,G,T.length,T+"","ext",c+"")')
    // e.func = e.func.replace('D4=function(c,k,G,n,S,y,T,t,m,u){for(0;c.H==c;![]!=0){{T=H(c,k)', 'D4=function(c,k,G,n,S,y,T,t,m,u){for(0;c.H==c;![]!=0){{T=H(c,k),pppp(14,k,T.length,T+"","ext",n+"")')
    // e.func = e.func.replace('M=function(c,k,G){','M=function(c,k,G){317!==k&&pppp("M",k,G);');
    // e.func = e.func.replace('A=function(c,k,G,n){', 'A=function(c,k,G,n){pppp("genLen", c);')
    // e.func = e.func.replace('X=function(c,k,G){', 'X=function(c,k,G){317!==c&&pppp("X",c,G);')
    // e.func = e.func.replace('f=function(c,k,G){', 'f=function(c,k,G){if(c===114&&G+""==+"-1640531527,-1640531527,314159265"){debugger;};317!==c&&pppp("f",c,G);')
    // e.func = e.func.replace('n.concat=function(D){k=D}', 'n.concat=function(D){pppp("sss", D);k=D}')
    // e.func = e.func.replace('TD=function(c,k,G,n,S,y,T,t){', 'TD=function(c,k,G,n,S,y,T,t){pppp("TD",k,n,S);')
    // e.func = e.func.replace('R(a.slice(b,(b|0)+(I|0)),q)', 'pppp("111",b,a,q),R(a.slice(b,(b|0)+(I|0)),q),pppp("222",b,a,q)')
    let userCode = `
    var _replace = String.prototype.replace;
var _match = String.prototype.match;
String.prototype.replace = function (oldStr, newStr) {
    // console.log('_replace',oldStr,  this)
    if (newStr === '\\n') {
        console.log('_replace', oldStr, this.toString())
        // if (this.toString().length === 7){
        // debugger;
        // }

        // debugger;
    }
    let res = _replace.apply(this, arguments)
    return res;

}
// String.prototype.match = function (mm){
//     let res = _match.apply(this, arguments)
//     print('_match', this.toString(), mm, '=', res);
//     return res;
// }

var _btoa = btoa;
btoa = function (pattern) {
    let res = _btoa(pattern);
    console.log(pattern.split('').map(e => e.charCodeAt(0)) + '');
    return res;

};

    ` + e.func + `;;

    var wwb = "${e.long_str}";;

    const c = new window.ridgeslice.gc(wwb);
window.sign = c;`

    // fs.writeFileSync('./tests/glf1.js', userCode)
    // let userCode = fs.readFileSync('tests/dy.js', 'utf8').toString();
// let userCode = fs.readFileSync('/Users/wang/Documents/jsvmp/learn/ksada/out2.js', 'utf8').toString();
    let html = fs.readFileSync('demo.html', 'utf8').toString();

    //
    // let a = "[null,\"[[null,\\\"CjRIR0hFOFRndDZLQzRBQV9nNFFCRy0tLS0tLS0tLXBmeGEyNkFBQUFBR2RRRzhjRlY4cE1BEgVXUzYwMBoLCLOfARACGgNDQUQ4HHCkcQ==\\\"],[null,null,1,null,[],1,[1,0,0,0],null,null,null,null,null,null,[[[[[\\\"YXE\\\",0]]],[[[\\\"YYC\\\",0]]],null,0,null,null,\\\"2024-12-15\\\",null,[[\\\"YXE\\\",\\\"2024-12-15\\\",\\\"YYC\\\",null,\\\"WS\\\",\\\"645\\\"]],null,null,null,null,null,3],[[[[\\\"YYC\\\",0]]],[[[\\\"YXE\\\",0]]],null,0,null,null,\\\"2024-12-29\\\",null,[[\\\"YYC\\\",\\\"2024-12-29\\\",\\\"YXE\\\",null,\\\"WS\\\",\\\"600\\\"]],null,null,null,null,null,3]],null,null,null,1],null,0]\"]";
    // new Promise((e, r) => {
    //     context.sign.ply(e, !0, Object.fromEntries([['mgGpzd', a]]))
    // })
    //     .then(e => {
    //     fetch("https://www.google.com/_/FlightsFrontendUi/data/travel.frontend.flights.FlightsFrontendService/GetBookingResults?f.sid=-5490820794450512428&bl=boq_travel-frontend-flights-ui_20241204.02_p0&hl=en-US&gl=CA&soc-app=162&soc-platform=1&soc-device=1&_reqid=63032&rt=c", {
    //         "headers": {
    //             "accept": "*/*",
    //             "accept-language": "en",
    //             "cache-control": "no-cache",
    //             "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
    //             "pragma": "no-cache",
    //             "priority": "u=1, i",
    //             "sec-ch-ua": "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"",
    //             "sec-ch-ua-arch": "\"arm\"",
    //             "sec-ch-ua-bitness": "\"64\"",
    //             "sec-ch-ua-form-factors": "\"Desktop\"",
    //             "sec-ch-ua-full-version": "\"131.0.6778.70\"",
    //             "sec-ch-ua-full-version-list": "\"Google Chrome\";v=\"131.0.6778.70\", \"Chromium\";v=\"131.0.6778.70\", \"Not_A Brand\";v=\"24.0.0.0\"",
    //             "sec-ch-ua-mobile": "?0",
    //             "sec-ch-ua-model": "\"\"",
    //             "sec-ch-ua-platform": "\"macOS\"",
    //             "sec-ch-ua-platform-version": "\"15.1.0\"",
    //             "sec-ch-ua-wow64": "?0",
    //             "sec-fetch-dest": "empty",
    //             "sec-fetch-mode": "cors",
    //             "sec-fetch-site": "same-origin",
    //             "x-goog-batchexecute-bgr": "[\";"+e+"\",null,null,572,54,null,null,0,\"5\"]",
    //             "x-goog-ext-259736195-jspb": "[\"en-US\",\"CA\",\"CAD\",1,null,[-480],null,[[97840014,97807935,97841892,72624439,97902459]],7,[]]",
    //             "x-same-domain": "1",
    //             "cookie": "AEC=AZ6Zc-W-bRmDzsjfS7V_i3fzkC0ppjY3fWVpLLWRW_3b-HBOX1gUTIq5EA; OTZ=7849557_24_24__24_; NID=519=Z4sBbzic4HDrxv9RYpKv74OCnvvGfPU2Ofn0-o8iPC33PpMdRJaHALpMxzzh3dm_vfusAh0ItWPkMXnQJMiEa5Q4wpsyOtf6csljcJ5SzSELg7nI8Zt1JhVKp2Hy74zJ4JwtzIM6ct4h-WUoZ_diAJOlzvmuT_sWP8K8GU_qUG6AyuTPYVu6f0VjxUnSBxpVuxO6R8_0cjjEQzT02tAfsw",
    //             "Referer": "https://www.google.com/travel/flights/booking?tfs=CBwQAho_EgoyMDI0LTEyLTE1Ih8KA1lYRRIKMjAyNC0xMi0xNRoDWVlDKgJXUzIDNjQ1agcIARIDWVhFcgcIARIDWVlDGj8SCjIwMjQtMTItMjkiHwoDWVlDEgoyMDI0LTEyLTI5GgNZWEUqAldTMgM2MDBqBwgBEgNZWUNyBwgBEgNZWEVAAUgBcAGCAQsI____________AZgBAQ&tfu=CmxDalJJUjBoRk9GUm5kRFpMUXpSQlFWOW5ORkZDUnkwdExTMHRMUzB0TFhCbWVHRXlOa0ZCUVVGQlIyUlJSemhqUmxZNGNFMUJFZ1ZYVXpZd01Cb0xDTE9mQVJBQ0dnTkRRVVE0SEhDa2NRPT0SAggAIgMSATA&gl=CA",
    //             "Referrer-Policy": "strict-origin-when-cross-origin"
    //         },
    //         "body": "f.req=%5Bnull%2C%22%5B%5Bnull%2C%5C%22CjRIR0hFOFRndDZLQzRBQV9nNFFCRy0tLS0tLS0tLXBmeGEyNkFBQUFBR2RRRzhjRlY4cE1BEgVXUzYwMBoLCLOfARACGgNDQUQ4HHCkcQ%3D%3D%5C%22%5D%2C%5Bnull%2Cnull%2C1%2Cnull%2C%5B%5D%2C1%2C%5B1%2C0%2C0%2C0%5D%2Cnull%2Cnull%2Cnull%2Cnull%2Cnull%2Cnull%2C%5B%5B%5B%5B%5B%5C%22YXE%5C%22%2C0%5D%5D%5D%2C%5B%5B%5B%5C%22YYC%5C%22%2C0%5D%5D%5D%2Cnull%2C0%2Cnull%2Cnull%2C%5C%222024-12-15%5C%22%2Cnull%2C%5B%5B%5C%22YXE%5C%22%2C%5C%222024-12-15%5C%22%2C%5C%22YYC%5C%22%2Cnull%2C%5C%22WS%5C%22%2C%5C%22645%5C%22%5D%5D%2Cnull%2Cnull%2Cnull%2Cnull%2Cnull%2C3%5D%2C%5B%5B%5B%5B%5C%22YYC%5C%22%2C0%5D%5D%5D%2C%5B%5B%5B%5C%22YXE%5C%22%2C0%5D%5D%5D%2Cnull%2C0%2Cnull%2Cnull%2C%5C%222024-12-29%5C%22%2Cnull%2C%5B%5B%5C%22YYC%5C%22%2C%5C%222024-12-29%5C%22%2C%5C%22YXE%5C%22%2Cnull%2C%5C%22WS%5C%22%2C%5C%22600%5C%22%5D%5D%2Cnull%2Cnull%2Cnull%2Cnull%2Cnull%2C3%5D%5D%2Cnull%2Cnull%2Cnull%2C1%5D%2Cnull%2C0%5D%22%5D&",
    //         "method": "POST"
    //     }).then(e => {
    //         return e.text()
    //     }).then(e => {
    //         console.log(e.length)
    //     })
    // }).catch(e => {
    //     debugger;
    //     print(e)
    // })
    // let {vm, context} = initVmSync(userCode, config, html)
    //

    let {vm, context} = initVmSync(userCode, config, html)

    let a = "[null,\"[[null,\\\"CjRIS2tscFpWR1ZmNVlBQlNXQ0FCRy0tLS0tLS0tLS10YmwzNUFBQUFBR2N5NDNjS281TmFBEgVXUzQ1NBoKCIcfEAAaA0hLRDgccKaPAw==\\\"],[null,null,1,null,[],1,[1,0,0,0],null,null,null,null,null,null,[[[[[\\\"YXE\\\",0]]],[[[\\\"YYC\\\",0]]],null,0,null,null,\\\"2024-11-19\\\",null,[[\\\"YXE\\\",\\\"2024-11-19\\\",\\\"YYC\\\",null,\\\"WS\\\",\\\"359\\\"]],null,null,null,null,null,3],[[[[\\\"YYC\\\",0]]],[[[\\\"YXE\\\",0]]],null,0,null,null,\\\"2024-12-02\\\",null,[[\\\"YYC\\\",\\\"2024-12-02\\\",\\\"YXE\\\",null,\\\"WS\\\",\\\"454\\\"]],null,null,null,null,null,3]],null,null,null,1],null,0]\"]";
    // a = req.body
    new Promise((e, r) => {
        console.log()
        context.sign.ply(e, !0, Object.fromEntries([['mgGpzd', a]]))
    }).then(e => {
        debugger;
        console.log(e)
        print(e.length)
        let t2 = Date.now();
    }).catch(e => {
        debugger;
        print(e)
    })

    const app = express()
// parse application/x-www-form-urlencoded
// parse application/json
    app.use(bodyParser.json({limit: '50mb'}));
    app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
    app.post('/bgr', async (req, res) => {
        let t1 = Date.now();

        let a = "[null,\"[[null,\\\"CjRIS2tscFpWR1ZmNVlBQlNXQ0FCRy0tLS0tLS0tLS10YmwzNUFBQUFBR2N5NDNjS281TmFBEgVXUzQ1NBoKCIcfEAAaA0hLRDgccKaPAw==\\\"],[null,null,1,null,[],1,[1,0,0,0],null,null,null,null,null,null,[[[[[\\\"YXE\\\",0]]],[[[\\\"YYC\\\",0]]],null,0,null,null,\\\"2024-11-19\\\",null,[[\\\"YXE\\\",\\\"2024-11-19\\\",\\\"YYC\\\",null,\\\"WS\\\",\\\"359\\\"]],null,null,null,null,null,3],[[[[\\\"YYC\\\",0]]],[[[\\\"YXE\\\",0]]],null,0,null,null,\\\"2024-12-02\\\",null,[[\\\"YYC\\\",\\\"2024-12-02\\\",\\\"YXE\\\",null,\\\"WS\\\",\\\"454\\\"]],null,null,null,null,null,3]],null,null,null,1],null,0]\"]";
        // a = req.body
        a = req.body.args
        context.sign = context.window.ridgeslice.gc(context.window.wwb)
        new Promise((e, r) => {
            console.log()
            context.sign.ply(e, !0, Object.fromEntries([['mgGpzd', a]]))
        }).then(e => {
            debugger;
            print(e)
            print(e.length)
            let t2 = Date.now();
            // console.log('cost ', (t2 - t1))
            res.send(e);
        }).catch(e => {
            debugger;
            print(e)
        })

        // v8.writeHeapSnapshot('1.heapsnapshot')

    })
    app.get('/heapdump', async (req, res) => {
        // console.log('reload vm');
        heapdump.writeSnapshot('./heapdump.heapsnapshot');
        // console.log("reload vm end");
        res.send({'code': true});
    })
    app.get('/gc', async (req, res) => {
        // console.log('reload vm');
        // global.gc()
        vm = null;
        context = null;
        // console.log("reload vm end");
        res.send({'code': true});
    })
    app.listen(3100, () => {
        // console.log(`Example app listening on port ${3100}`)
    })

})
